package com.gzs.zhdj.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gzs.zhdj.constant.RoleConstant;
import com.gzs.zhdj.context.BaseContext;
import com.gzs.zhdj.domain.dto.PageBean;
import com.gzs.zhdj.domain.dto.PartyMemberPageDto;
import com.gzs.zhdj.domain.entity.PartyMember;
import com.gzs.zhdj.domain.dto.PartyMemberDto;
import com.gzs.zhdj.domain.dto.PasswordEditDto;
import com.gzs.zhdj.exception.FileErrorException;
import com.gzs.zhdj.exception.PasswordEditFailedException;
import com.gzs.zhdj.exception.PasswordErrorException;
import com.gzs.zhdj.mapper.AdminMapper;
import com.gzs.zhdj.mapper.OrganizationMapper;
import com.gzs.zhdj.service.AdminService;
import com.gzs.zhdj.exception.AccountErrorException;
import com.gzs.zhdj.constant.MessageConstant;
import com.gzs.zhdj.utils.AliOssUtil;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class AdminServiceImpl implements AdminService {
    private static final Logger log = LoggerFactory.getLogger(AdminServiceImpl.class);
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    OrganizationMapper organizationMapper;
    //导入用户
    @Override
    public void importUser(PartyMemberDto partyMemberDto) {
        PartyMember partyMember = new PartyMember();
        String username = partyMemberDto.getName();
        StringBuilder firstLetter = new StringBuilder();
        // 将用户名的每个字符转换为拼音并获取首字母
        for (char ch : username.toCharArray()) {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(ch);
            if (pinyinArray != null && pinyinArray.length > 0) {
                firstLetter.append(pinyinArray[0].charAt(0)); // 取拼音的首字母
            }
        }
        String firstletter = firstLetter.toString().toLowerCase();

        // 默认初始密码
        String defaultPassword = "123456" + firstletter;
        //加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(defaultPassword.getBytes());
        partyMemberDto.setPassword(encryptedPassword);
        BeanUtils.copyProperties(partyMemberDto , partyMember);
        int id = BaseContext.getCurrentId();
        int o_id = adminMapper.getOidById(id);
        partyMember.setPartyId(o_id);
        adminMapper.insert(partyMember);

    }

    @Override
    //根据id修改密码
    public void updatePasswordById(PasswordEditDto passwordEditDto) {
        if (!passwordEditDto.getNewPassword1().equals(passwordEditDto.getNewPassword2())) {
            throw new PasswordErrorException(MessageConstant.NEW_PASSWORD_DIFFERENT);
        }
        String encryptedPassword = DigestUtils.md5DigestAsHex(passwordEditDto.getNewPassword2().getBytes());
        passwordEditDto.setNewPassword2(encryptedPassword);
        adminMapper.updatePasswordById(passwordEditDto);
    }

    //根据ID查询党员信息
    @Override
    public PartyMember getById(Integer id) {
        return adminMapper.getById(id);
    }


    @Override
    public PartyMember adminLogin(PartyMemberDto partyMemberDto) {
        int id = partyMemberDto.getId();

        String password = partyMemberDto.getPassword();
        PartyMember partyMember = adminMapper.getById(id);
        if(!(partyMember.getRole()).equals(RoleConstant.ADMIN))
        {
            throw new AccountErrorException(MessageConstant.ADMIN_ROLR_ERROR);
        }
        if (partyMember == null) {
                //账号不存在
                throw new AccountErrorException(MessageConstant.ACCOUNT_ERROR);
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(partyMember.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        return partyMember;
    }

    @Override
    public PageBean page(@RequestBody PartyMemberPageDto partyMemberPageDto) {
        PageHelper.startPage(partyMemberPageDto.getPage(), partyMemberPageDto.getPageSize());

        Page<PartyMember> page = adminMapper.pageQuery(partyMemberPageDto);

        long total = page.getTotal();
        List<PartyMember> records = page.getResult();

        return new PageBean(total, records);
    }
    public void updatePassword(PasswordEditDto passwordEditDto) {
        int id = BaseContext.getCurrentId();
        PartyMember partyMember = adminMapper.getById(id);
        if (passwordEditDto.getOldPassword().equals(passwordEditDto.getNewPassword2())) {
            throw new PasswordEditFailedException(MessageConstant.O_N_PASSWORD_ERROR);
        }
        if (!DigestUtils.md5DigestAsHex(passwordEditDto.getOldPassword().getBytes()).equals(partyMember.getPassword())) {
            throw new PasswordEditFailedException(MessageConstant.OLD_PASSWORD_ERROR);
        }
        if (!passwordEditDto.getNewPassword1().equals(passwordEditDto.getNewPassword2())) {
            throw new PasswordEditFailedException(MessageConstant.NEW_PASSWORD_DIFFERENT);
        }
        String encryptedPassword = DigestUtils.md5DigestAsHex(passwordEditDto.getNewPassword2().getBytes());
        passwordEditDto.setId(id);
        passwordEditDto.setNewPassword2(encryptedPassword);
        adminMapper.updatePassword(passwordEditDto);
    }

    @Override
    public PartyMember getSelfInfo() {
        int id = BaseContext.getCurrentId();
        PartyMember member = adminMapper.getById(id);
        return member;
    }

    @Override
    public void updateSelfInof(PartyMember partyMember) {
        int id = BaseContext.getCurrentId();
        partyMember.setId(id);
        adminMapper.update(partyMember);
    }

    @Override
    public void upload(MultipartFile file) {
        try {
            int id = BaseContext.getCurrentId();
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //检查文件格式是否为图片
            String[] allowedExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"};
            boolean isValidFormat = false;
            for (String ext : allowedExtensions) {
                if (extension.equals(ext)) {
                    isValidFormat = true;
                    break;
                }
            }
            if (!isValidFormat) {
                throw new FileErrorException("文件格式错误，只允许上传图片格式文件");
            }
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            adminMapper.upload(id, filePath);
        } catch (IOException e) {
//            throw new F
        }
    }

    @Override
    public List<Integer> getId() {
        List<Integer> ids = adminMapper.getId();
        return ids;
    }

    @Override
    public String getOrgName() {
        int id = BaseContext.getCurrentId();
        int o_id = adminMapper.getOidById(id);
        return organizationMapper.getOrgNameById(o_id);
    }
    public void updateInfoById(PartyMember partyMember) {
        adminMapper.updateInfoById(partyMember);
    }

}
